/* TestOutputXml.cpp
*
*  Created by Penrillian, Smartphone Software Innovators 
*  See http://www.penrillian.com
*/

#include "cxxtest/TestOutputXml.h"
#include <bautils.h>



CTestOutputXml* CTestOutputXml::NewL(HBufC* aOutputText)
{
	CTestOutputXml* eikConsole = new (ELeave) CTestOutputXml(aOutputText);
	CleanupStack::PushL(eikConsole);
	eikConsole->ConstructL();
	CleanupStack::Pop();
	return eikConsole;
}


CTestOutputXml::~CTestOutputXml()
{
	iFile.Close();
	iRfs.Close();
}



void CTestOutputXml::ConstructL()
{
	User::LeaveIfError(iRfs.Connect());
	TParse parse;
	parse.Set(KLogFileNameXml,NULL,NULL);
	if(!BaflUtils::FolderExists(iRfs,parse.DriveAndPath()))
		User::LeaveIfError(iRfs.MkDir(parse.DriveAndPath()));

	User::LeaveIfError(iFile.Replace(iRfs,KLogFileNameXml,EFileWrite));

	PrintSuccessfulTests = false;
}

CTestOutputXml& CTestOutputXml::operator<<(const char* output)
{	
	const TText8 * buf=(const TText8*) (output);	
	TPtrC8 temp(buf,strlen(output));
	return operator<<(temp);								
}	

CTestOutputXml& CTestOutputXml::operator<<(TDesC8& _des)
{
	TRAPD(err,WriteToXmlFileL(_des));
	if(err != KErrNone)
		iOutputText->Des().Append(_L("Error Writing to xml file !"));
	return *this;
}

void CTestOutputXml::WriteToXmlFileL(TDesC8& _des)
{
	HBufC8* des = HBufC8::NewLC(_des.Length()+3);
	TPtr8 buf = des->Des();
	buf.Append(_des);
	
	iFile.Write(*des);
	
	CleanupStack::Pop(des);
	delete des;
}


void CTestOutputXml::ReplaceNumofTests(TInt failedTestsNo/*, TInt numTotalTests*/)
{
	TBuf8<128> readBuf;
	
	if (iFile.Read(0, readBuf, 128)!= KErrNotFound )
	{
		_LIT8(KSearchString, "****");
		TBuf8<8> searchString(KSearchString());
		
		
		TInt aPos = 0;
		aPos = readBuf.Find( searchString );
		
		if (aPos != KErrNotFound && aPos != 0)
		{
			TBuf8<8> writeBuf;
			writeBuf.AppendNum(failedTestsNo);
			
			if ( writeBuf.Length() < 4 )
			{
				TInt i = 4 - writeBuf.Length();
				while (i > 0)
				{
					_LIT8(KBlankChar, " ");
					TBuf8<8> blankChar(KBlankChar());
					writeBuf.Append(blankChar);
					i--;
				}
			}
			
			iFile.Write(aPos, writeBuf);
		}
	}
	else
	{
		User::InfoPrint(_L("Missing xml file!"));
	}
}